<?php

namespace nabu\libs\emails;

defined('NABU') || exit;

require_once 'libs/php-smtp-2.0.4/Email.php';

use Snipworks\Smtp\Email;

// Envía mensajes de e-mail en formato HTML.
class emails {
  private $mail;

  // Configuración del cliente SMTP.
  public function __construct() {
    // Carga el archivo de configuración.
    $config = include_once NABU_DIRECTORY['email'];

    global $messages;

    if (empty($config) || !is_array($config))
      $messages -> errors('The email configuration file is not an array', 400);

    if (empty($config['smtp']) || empty($config['port']) || empty($config['address'])
        || empty($config['password']))
      $messages -> errors('Set smtp, port, address and password in the configuration file', 400);

    // Configura el cliente del e-mail.
    $this -> mail = new Email($config['smtp'], $config['port']);
    $this -> mail -> setProtocol(Email::TLS);
    $this -> mail -> setLogin($config['address'], $config['password']);
    $this -> mail -> setFrom($config['address'], NABU_DEFAULT['name']);
  }

  // Define el destinatario del mensaje.
  public function prepare(string $destinatary, string $name) {
    $this -> mail -> addTo($destinatary, $name);
  }

  // Envía un mensaje de e-mail.
  public function send(string $subject, string $body) {
    $this -> mail -> setSubject($subject);

    $this -> mail -> setHtmlMessage($body);

    return $this -> mail -> send();
  }

  public function __destruct() {
    $this -> mail = null;
  }
}
